<?php
/**
 * Created by PhpStorm.
 * User: Raytine
 * Date: 2019/11/29
 * Time: 15:23
 */

namespace app\api\controller\android\v13;

use app\api\model\AlibabaCloudToke;
use app\api\model\OrderDeliveryManagerModel;
use app\api\model\DetailedWorkProcess;
use app\api\model\OrderModel;
use app\api\model\StartupNewHandover;
use think\Exception;
use think\Controller;
use think\Request;
use redis\RedisPackage;
use app\api\model\Authority;
use app\api\model\Common;
use app\api\model\Capital;
use app\api\model\Approval;
use Carbon\Carbon;
use think\Db;



class Artificial extends Controller
{
    protected $us;
    
    public function _initialize()
    {
        $this->us = Authority::check(1);
    }
    
    /**
     * 日报参数
     */
    protected function day_param($max = 3)
    {
        $param = Request::instance()->post();
        if (empty($param['start_date'])) {
            r_date(null, 300, "开始时间不能为空");
        }
        if (empty($param['end_date'])) {
            r_date(null, 300, "结束时间不能为空");
        }
        $start = date("Y-m-d", strtotime($param['start_date']));
        $end   = date("Y-m-d", strtotime($param['end_date']));
        //两个时间差的天数
        $day = day_value($start, $end);
        if ($day < 0) {
            r_date(null, 300, "开始时间不能小于结束时间");
        }
        //两个时间差的月数
        $month = month_value($start, $end);
        if ($month > $max) {
            r_date(null, 300, "时间跨度不能超过" . $max . "月");
        }
        
        return [
            'start_date' => $start,
            'end_date' => $end,
            'start_timestamp' => strtotime($start . ' 00:00:00'),
            'end_timestamp' => strtotime($end . ' 23:59:59'),
            'type' => isset($param['type']) ? $param['type'] : 1,
            'Difference' => isset($param['Difference']) ? $param['Difference'] : 1,
            'day' => $day,
            'month' => $month,
            'user_id' => isset($param['user_id']) ? $param['user_id'] : $this->us['user_id'],
        ];
    }
    
    public function user_list()
    {
        $cap = db('user')->where('store_id', $this->us['store_id'])->field('reserve,user_id,username')->select();
        r_date($cap, 200);
    }
    
    /*
     * 材料计算
     */
    
    public function Cost(OrderModel $orderModel,OrderDeliveryManagerModel $deliveryManagerModel)
    {
        $data            = Authority::param(['order_id', 'type']);
        $order_id        = $data['order_id'];
        $order_times             = db('order_times') ->where('order_id', $order_id)->field('order_times.change_work_time,order_times.signing_time')->find();
        $order_start_delay             = db('order_start_delay') ->where('order_id', $order_id)->value('delay_days');
        $de              = db('startup')
            ->join('order', 'order.order_id=startup.orders_id', 'left')
            ->join('order_times', 'order_times.order_id=startup.orders_id', 'left')
            ->where('startup.orders_id', $order_id)
            ->field('startup.sta_time,startup.up_time,startup.con,startup.handover,startup.xiu_id,startup.startup_id,order.start_time')
            ->find();
        $startup_new_handover=db('startup_new_handover')->field('sum(if(type=1,1,0)) as type1,sum(if(type=2,1,0)) as type2') ->where('order_id', $order_id)->where('delete_time', 0)->select(); 
    
        $cap             = $orderModel->ManualSettlement($order_id);   
        $cap['sta_time'] = !empty($de['sta_time']) ? date('Y-m-d', $de['sta_time']) : '';
        $cap['up_time']  = !empty($de['up_time']) ? date('Y-m-d', $de['up_time']) : '';
        $cap['state']    = empty($de['start_time']) ? 0 : 1;
        $cap['signingTime']    =date('Y-m-d H:i:s',$order_times['signing_time']) ;
        $orderState=1;
        if(!empty($order_times['signing_time']) && empty($order_times['change_work_time'])){
            $orderState=0;
        } 
    //    $user=new User();
    //    $mobel=$user->switchUserMobel();
       $cap['deliverState']    =0;
       $cap['deliverState']    =0;
       if($this->us['is_handover']==1){
        $cap['deliverState']    =1;
       }
       $cap['deliverTitle']    ="销售完成签约后，请下载此交接文档，与交付负责人完成详细内容的确认。指派交付负责人后，对方也会看到此文档。(若城市没有此规范，可忽略)";
       $cap['deliverUrl']    ="http://".$_SERVER['HTTP_HOST'].'/api/Tongji/exportWord?city='.config('city').'&orderId='.$order_id;
        $cap['orderState']    =$orderState;
        $cap['orderDeliveryManager'] = $deliveryManagerModel->StartupDeliverer($order_id);
        $cap['handoverState']=0;
        if($startup_new_handover[0]['type1'] !=0 && $startup_new_handover[0]['type2'] !=0){
            $cap['handoverState']=1; 
        }
        $countdown=(strtotime(date('Y-m-d 00:00:00', $order_times['change_work_time']))+4*24*3600+($order_start_delay*24*3600))-time();
        if($countdown<0){
            $countdown=0;
        }
        $cap['countdown'] = !empty($de['sta_time'])?0:$countdown;
        $cap['strongRegulations'] = '签约后，3天内必须确认开工日期、做好交底数据与前两道工序施工人员。到达开工日期后系统会自动开工，若干无法按时开工请操作延期开工，每个项目仅可延期开工一次，请仔细确认时间后操作。';
        $cap['titleAdd'] = '如签约3日内仍然无法确认开工时间，请添加延期开工说明，否则系统将限制您的APP操作。';
        //是否显示添加按钮
        $addButton=0;
        if(empty($de['sta_time']) && empty($order_start_delay)){
            $addButton=1;
        }
        if($order_times['signing_time']<1718294400){
            $addButton=0;
        }
        $cap['addButton'] =  $addButton;
        $cap['constructionAnnotation'] = '
        1、确认开工时间后，什么条件触发开工？
        首个入场师傅入场点击开工打卡后(适用于第一进场师傅有APP)；交付负责人/店长也可点击开工(适用于第一进场师傅为外协)
        2、开工日期如何设置？
        签约日3日内，需要和用户确认完成开工日期，若无法确定请推迟确认时间
        3、注意事项：
        开工时间确定一次，会给用户发一次短信，请谨慎设置，避免乱填；施工日期系统会自动过滤节假日。
        ';
        if (empty($cap['data'])) {
            r_date($cap, 200);
        }
        $app_user_order_capital_relation = Db::connect(config('database.db2'))->table('app_user_order_capital_relation')->whereIn('user_id', $de['xiu_id'])->join('app_user', 'app_user.id=app_user_order_capital_relation.user_id', 'left')->field('if(app_user.quit_jobs=1,concat(app_user.username,"【已离职】"),app_user.username) as username,app_user.id,app_user_order_capital_relation.capital_id,app_user.origin as origins')->whereNull('app_user_order_capital_relation.deleted_at')->where('order_id', $order_id)->select();
        $app_user1                       = Db::connect(config('database.db2'))->table('app_user_order')->whereIn('user_id', $de['xiu_id'])->join('app_user', 'app_user.id=app_user_order.user_id', 'left')->field('app_user.username,app_user.origin as origins,app_user.id')->where('app_user_order.status','<>',10)->where('order_id', $order_id)->select();
        //本店铺所有的师傅
        $appUser       = Db::connect(config('database.db2'))->table('app_user')->where('store_id', $this->us['store_id'])->where('status', 1)->group('work_type_id')->field('id,work_type_id,if(quit_jobs=1,concat(username,"【已离职】"),concat(username,"【已离职】")) as username')->select();
        $almighty      = [];
        $carpentry     = [];
        $painter       = [];
        $Bricklayer    = [];
        $electrician   = [];
        $KnockDown     = [];
        $order_setting = \db('order_setting')->where('order_id', $order_id)->find();
        foreach ($appUser as $k => $v) {
            switch ($v['work_type_id']) {
                //全能工
                case 1:
                    $almighty[] = $v;
                    break;
                //木工
                case 2:
                    $carpentry[] = $v;
                    break;
                //漆工
                case 3:
                    $painter[] = $v;
                    break;
                //砖工
                case 4:
                    $Bricklayer[] = $v;
                    break;
                //电工
                case 5:
                    $electrician[] = $v;
                    break;
                //打拆协作
                case 8:
                    $KnockDown[] = $v;
                    break;
                
            }
        }
        
        $result   = array();
        $tageList = [];
        
        if ($data['type'] == 1) {
            foreach ($cap['data'] as $k => $v) {
                switch ($v['id']) {
                    //拆除类
                    case 1:
                        $cap['data'][$k]['mastUsername'] = empty($KnockDown) ? $almighty : $KnockDown;
                        break;
                    //油漆工类 防水类
                    case 2:
                    case 6:
                        $cap['data'][$k]['mastUsername'] = empty($painter) ? $almighty : $painter;
                        break;
                    //泥瓦工类
                    case 3:
                        $cap['data'][$k]['mastUsername'] = empty($Bricklayer) ? $almighty : $Bricklayer;
                        break;
                    //木工类
                    case 4:
                        $cap['data'][$k]['mastUsername'] = empty($carpentry) ? $almighty : $carpentry;
                        break;
                    //水电工类
                    case 5:
                        $cap['data'][$k]['mastUsername'] = empty($electrician) ? $almighty : $electrician;
                        break;
                    //其他
                    default :
                        $cap['data'][$k]['mastUsername'] = [];
                        break;
                    
                }
                $cap['data'][$k]['masterSalaryRate'] = $order_setting['master_salary_rate'];
                
            }
            if (!empty($app_user_order_capital_relation)) {
                foreach ($cap['data'] as $k => $v) {
                    $users = [];
                    foreach ($app_user_order_capital_relation as $value) {
                        if (!empty($value['capital_id']) && $value['capital_id'] == $v['projectId']) {
                            $value['personalPrice']     = Db::connect(config('database.db2'))->table('app_user_order_capital')->where('capital_id',$value['capital_id'])->where('user_id', $value['id'])->whereNull('deleted_at')->value('personal_price');
                            if($value['origins']==2){
                                $value['personalPrice']     = Db::connect(config('database.db2'))->table('app_user_order_capital')->where('capital_id',$value['capital_id'])->whereNull('deleted_at')->value('cooperation_price');
                            }
                            $users[] = $value;
                        }
                        
                    }
                    
                    $cap['data'][$k]['mastUsername']     = array_merge($users, $v['mastUsername']);
                    $cap['data'][$k]['totalLaborCost']     = array_sum(array_column($users,'personalPrice'));
                    $cap['data'][$k]['masterSalaryRate'] = $order_setting['master_salary_rate'];
                    $cap['data'][$k]['finallyIncludedInCost'] =bcadd(array_sum(array_column($users,'personalPrice')),$v['laborCostReimbursement'],2);
                }
            }
            
        } else {
            if (!empty($app_user_order_capital_relation)) {
                foreach ($cap['data'] as $k => $v) {
                    $users = [];
                    foreach ($app_user_order_capital_relation as $value) {
                        if (!empty($value['capital_id']) && $value['capital_id'] == $v['projectId']) {
                            $value['personalPrice']     = Db::connect(config('database.db2'))->table('app_user_order_capital')->where('capital_id',$value['capital_id'])->where('user_id', $value['id'])->whereNull('deleted_at')->value('personal_price');
                            if($value['origins']==2){
                                $value['personalPrice']     = Db::connect(config('database.db2'))->table('app_user_order_capital')->where('capital_id',$value['capital_id'])->whereNull('deleted_at')->value('cooperation_price');
                            }
                            $users[] = $value;
                        }
                        
                    }
                    $cap['data'][$k]['mastUsername']     = $users;
                    $cap['data'][$k]['totalLaborCost']     = array_sum(array_column($users,'personalPrice'));
                    $cap['data'][$k]['masterSalaryRate'] = $order_setting['master_salary_rate'];
                    $cap['data'][$k]['finallyIncludedInCost'] =bcadd(array_sum(array_column($users,'personalPrice')),$v['laborCostReimbursement'],2);//最终成本费用
                }
            } else {
                foreach ($cap['data'] as $k => $v) {
                    $cap['data'][$k]['mastUsername']     = $app_user1;
                    $cap['data'][$k]['masterSalaryRate'] = $order_setting['master_salary_rate'];
                    $cap['data'][$k]['finallyIncludedInCost'] =$v['laborCostReimbursement'];
                }
                
            }
            
        }
        $type = 0;
        if (!empty($app_user1)) {
            $type = 1;
        }
          foreach ($cap['data'] as $k => $v) {
            $result[$v['titles']][] = $v;
        }
        foreach ($result as $k => $list) {
            $schemeTag['titles'] = $k;
            $schemeTag['data']   = $result[$k];
            $tageList[]          = $schemeTag;
        }
                $handover = null;
        if (!empty($de['handover']) && $de['handover'] != '') {
            
            $handoverList = unserialize($de['handover']);
            foreach ($handoverList as $k => $list) {
                $handover[$k]['imgUrl']  = $list;
                $handover[$k]['remarks'] = '';
            }
        } else {
            $startupHandover = db('startup_handover')->where('startup_id', $de['startup_id'])->field('img_url,remarks')->select();
            if ($startupHandover) {
                foreach ($startupHandover as $k => $list) {
                    $handover[$k]['imgUrl']  = $list['img_url'];
                    $handover[$k]['remarks'] = $list['remarks'];
                }
            }
            
        }
        $cap['handover']   = $handover;
        $cap['con']        = $de['con'];
        $cap['data']       = $tageList;
        $cap['type']       = $type;
        $cap['fastSalary'] = 0;
        r_date($cap, 200);
    }
    public function CostInfo()
    {
        $data            = Authority::param(['orderId']);
        $order_id        = $data['orderId'];
        
        $startup_new_handover=db('startup_new_handover') ->where('order_id', $order_id)->where('delete_time', 0)->select();
        $inspection_photos=db('through') ->where('order_ids', $order_id)->order('through_id desc')->where(function($quer){
            $quer->where('mode',"上门基检")->whereOr('mode',"客户需求与方案报告");
        })->value('inspection_photos');
        $customerDemand='';
        $workmanship='';
        $specialNeed='';
        $demandSpace=[];
        $changeSynchronization=[];
        foreach ($startup_new_handover as $key => $value) {
            if($value['type']==1){
                $customerDemand=['id'=>$value['id'],'content'=>$value['content']];
            }
            if($value['type']==2){
                $demandSpace[]=['id'=>$value['id'],'grouping'=>$value['grouping'],'images'=>json_decode($value['images']),'content'=>$value['content']];
            }
            if($value['type']==3){
                $changeSynchronization[]=['id'=>$value['id'],'app_work_type'=>$value['app_work_type'],'appWorkTypeId'=>$value['app_work_type'],'images'=>json_decode($value['images']),'content'=>$value['content'],'create_time'=>date('Y-m-d',$value['create_time'])];;
            }
            if($value['type']==4 && $value['pattern']==1){
                $workmanship=['id'=>$value['id'],'content'=>$value['content'],'pattern'=>$value['pattern'],'json'=>null];
            }
            if($value['type']==4 && $value['pattern']==2){
             
                $workmanship=['id'=>$value['id'],'content'=>'','pattern'=>$value['pattern'],'json'=>json_decode($value['template_json'],true)];
            }
            if($value['type']==5){
                $specialNeed=['id'=>$value['id'],'content'=>$value['content']];;
            }
        }
         if(empty($startup_new_handover)){
            $inspection_photos=db('through') ->where('order_ids', $order_id)->where('mode',"客户需求与方案报告")->order('through_id desc')->value('remar');  
            $customerDemand=['id'=>0,'content'=>$inspection_photos];
         }
    //     $de              = db('startup')
    //    ->where('startup.orders_id', $order_id)
    //     ->field('startup.xiu_id')
    //     ->find();

        $cap['workype']=db('work_type',config('database.zong'))->where(['status'=>1,'fixed_process'=>1])->field('id,title')->select();
        $cap['demandSpaces']=empty($demandSpace)?null:$demandSpace; //新施工交底 按照空间，对需求及施工要求详细描述 
        $cap['customerDemand']=empty($customerDemand)?null:$customerDemand;//新施工交底 请对客户需求整体描述
        $cap['workmanship']=empty($workmanship)?null:$workmanship;//新施工交底 请对客户需求整体描述
        $cap['specialNeed']=empty($specialNeed)?null:$specialNeed;//新施工交底 请对客户需求整体描述
        foreach ($changeSynchronization as $k => $v) {
        $username=[];
        $app_work_type=explode(",",$v['app_work_type']);
        foreach ($app_work_type as $v3) {
            foreach ($cap['workype'] as $v4) {
                if($v3==$v4['id']){
                    $username[]=$v4['title'];
                
                }
            }   
        
        }
        
        $changeSynchronization[$k]['username']= implode(",",array_unique($username)); 
        $changeSynchronization[$k]['app_work_type']= implode(",",array_unique($username));  
       }
       $cap['changeSynchronization']=empty($changeSynchronization)?null:$changeSynchronization;
      
       $capital = db('capital')->where(['capital.ordesr_id' => $order_id, 'capital.types' => 1, 'capital.enable' => 1, 'capital.agency' => 0])->where('ordesr_id', $order_id)->select();
       $categoryName =empty($capital)?null: array_merge(array_unique(array_column($capital,'categoryName')));
       $prompt='';
       if(!empty($inspection_photos) && empty( $cap['demandSpaces'])){
        $prompt='检测到沟通记录已上传上门基检照片，是否同步';
       }
       $kl=[];
       if(!empty($categoryName)){
        foreach($categoryName as $k=>$value){
            $kl[$k]['title']=$value;
            $kl[$k]['name']=$prompt;
           }
       }
       
       $cap['categoryName']=empty($kl)?null:$kl;
       
        r_date($cap, 200);
    }
    public function CostInfoHandover()
    {
        $data            = Authority::param(['id']);
        $id        = $data['id'];
        
        $startup_new_handover=db('startup_new_handover') ->where('id', $id)->where('pattern', 2)->where('delete_time', 0)->find();
        $sys_config= Db::connect(config('database.zong'))->table('sys_config') ->where('keyss', 'handover')->where('statusss', 1)->value('valuess');
        if($startup_new_handover['pattern']==2 && !empty($startup_new_handover['template_json'])){
            $sys_config=json_decode($startup_new_handover['template_json'],true);
        }
        $handover=json_decode($sys_config,true);
       
        r_date($handover, 200);
    }
    public function throughPhotos()
    {
        $data            = Authority::param(['orderId']);
        $order_id        = $data['orderId'];
        $inspection_photos=db('through') ->where('order_ids', $order_id)->where('mode',"客户需求与方案报告")->order('through_id desc')->value('inspection_photos');
        $inspection_photos=json_decode($inspection_photos,true);
        r_date($inspection_photos, 200);
    }

    /*
      * 提交人工报价
      */
    public function category(Common $common,DetailedWorkProcess $detailedWorkProcess, Capital $capital,RedisPackage $redis)
    {
        $data                               = Request::instance()->post();
        $op                                 = json_decode($data['company'], true);
        $handover                           = json_decode($data['handover'], true);
        $leaders                            = json_decode($data['leader'], true);
        if (empty($data['sta_time'])) {
            $common->isStart($data['order_id'],$this->us);
        }
        $app_user_order_capital_labor_costs = \db('app_user_order_capital_labor_costs')->field('user_id as masterId,capital_id as projectId')->where('order_id', $data['order_id'])->select();
        if (!empty($app_user_order_capital_labor_costs) && empty($leaders)) {
            r_date(null, 300, '已有快捷师傅不能为空');
        }
        if (!empty($leaders) && !empty($app_user_order_capital_labor_costs)) {
            $leaders = array_merge($leaders, $app_user_order_capital_labor_costs);
        }
        $data['shi_id'] = empty($leaders) ? '' : implode(array_unique(array_column($leaders, 'masterId')), ',');
        $leader         = empty($leaders) ? null : array_unique(array_column($leaders, 'masterId'));
        $order_setting   = \db('order_setting')->where('order_id', $data['order_id'])->find();
        $order_times   = \db('order_times')->where('order_id', $data['order_id'])->find();
        // 获取所有未删除记录
        $existingRecords = Db::connect(config('database.db2'))
            ->table('app_user_order_capital_relation')
            ->where(['order_id' => $data['order_id']])
            ->whereNull('deleted_at')
            ->select();
        // 获取所有未删除记录
        $appCapital = Db::connect(config('database.db2'))
            ->table('app_user_order_capital')
            ->where(['order_id' => $data['order_id']])
            ->whereNull('deleted_at')
            ->select();
        $app_user_confirm_order_list = db('app_user_confirm_order')
            ->where(['order_id' => $data['order_id']])
            ->where('delete_time', 0)
            ->select();
        db()->startTrans();
        try {

            $pri             = 0;
            $OldPri          = 0;
            $laborCcostPrice = 0;
            $projectId       = [];
            $result          = [];
            $redisKeysToDel=[];
            $redisKeysToyuyueDel = [];
            if (!empty($leaders)) {
                $projectMasterMap = []; // 项目-师傅映射，避免重复处理
                foreach ($leaders as $k => $v) {
                    $projectId = $v['projectId'];
                    $masterId = $v['masterId'];
                    $projectMasterMap[$projectId][] = $masterId;


                    // 如果有时间信息，更新确认订单记录
                    if (isset($v['time'])  && $v['time'] != 0) {
                        if (is_numeric($v['time'])) {
                            $v['time'] = $v['time'] / 1000;;
                        }else{
                           $v['time'] = strtotime($v['time']);  
                        }
                        $toDeleteConfirmOrder[] = [
                            'order_id' => $data['order_id'],
                            'app_user_id' => $v['masterId'],
                            'project_id' => $v['projectId']
                        ];
                        
                        $toInsertConfirmOrder[] = [
                            'order_id' => $data['order_id'],
                            'app_user_id' => $v['masterId'],
                            'project_id' => $v['projectId'],
                            'date' => $v['time'],
                            'status' => 0,
                            'create_time' => time()
                        ];
                        $redisKeysToDel[] = "DateAssignment-".md5($data['order_id'] . $v['projectId'] . 'time');
                        $redisKeysToyuyueDel[] ="DateAssignment-".md5($data['order_id'] . $v['projectId'] . 'yuyue');
                    }
                }
                // 批量处理op的masterId（避免嵌套循环）
                foreach ($op as $k1 => $item) {
                    $op[$k1]['masterId'] = $projectMasterMap[$item['projectId']] ?? [];
                }
            }
           
          
            $appUserConfirmOrderList = collect($app_user_confirm_order_list);
            $existingRecords = collect($existingRecords);
            $appCapital = collect($appCapital);


            // 准备JSON数据集合
            $jsonCollection = collect($leaders);

            // 构建JSON数据的哈希表（键为user_id和capital_id的组合）
            $jsonHash = [];
            foreach ($jsonCollection as $item) {
                $key = $item['masterId'] . '_' . $item['projectId'];
                $jsonHash[$key] = true;
            }


            // 找出需要删除的记录（使用哈希表匹配，时间复杂度O(1)）
            $recordsToDelete = $existingRecords->filter(function ($record) use ($jsonHash) {
                $key = $record['user_id'] . '_' .  $record['capital_id'];
                return !isset($jsonHash[$key]);
            });
            $recordsToDeleteCapital = $appCapital->filter(function ($record) use ($jsonHash) {
                $key = $record['user_id'] . '_' .  $record['capital_id'];
                return !isset($jsonHash[$key]);
            });
            $appUserConfirmDeleteCapital = $appUserConfirmOrderList->filter(function ($record) use ($jsonHash) {
                $key = $record['app_user_id'] . '_' .  $record['project_id'];
                return !isset($jsonHash[$key]);
            });
            $deleteTime = time();
            // 批量更新删除时间
            if (count($recordsToDelete) != 0) {
                $ids = $recordsToDelete->column('id');
                Db::connect(config('database.db2'))->table('app_user_order_capital_relation')->where(['order_id' => $data['order_id']])->whereIn('id', $ids)->update([
                    'deleted_at' => $deleteTime,
                    'cancel_shopowner' => 2
                ]);
            }
            // 批量更新删除时间
            if (count($recordsToDeleteCapital) != 0) {
                $idsCapital = $recordsToDeleteCapital->column('id');
                Db::connect(config('database.db2'))->table('app_user_order_capital')->where(['order_id' => $data['order_id']])->whereIn('id', $idsCapital)->update(['deleted_at' => $deleteTime, 'cancel_shopowner' => 2]);
            }
               // 批量更新删除时间
            if (count($appUserConfirmDeleteCapital) != 0) {
                $idsConfirm = $appUserConfirmDeleteCapital->column('id');
                Db::connect(config('database.db2'))->table('app_user_confirm_order')->where(['order_id' => $data['order_id']])->whereIn('id', $idsConfirm)->update(['delete_time' => $deleteTime]);
            }

            foreach ($op as $item) {
                $cooperation = 0;
                if (isset($item['masterId'])) {
                    $origin = db('app_user')->whereIn('id', $item['masterId'])->where('origin', 2)->count();
                    if ($origin > 0) {
                        $cooperation = 1;
                    }
                }

                $labor_cost_price = db('capital')->where(['capital_id' => $item['projectId']])->find();
                $requested_amount = ['labor_cost' => $item['pri'], 'material' => $item['material'], 'revised' => 1, 'cooperation' => $cooperation];
                if ($labor_cost_price['requested_amount'] == 0) {
                    $requested_amount                     = ['labor_cost' => $item['pri'], 'material' => $item['material'], 'revised' => 1, 'cooperation' => $cooperation, 'requested_amount' => bcmul($labor_cost_price['labor_cost_price'], $labor_cost_price['square'], 2)];
                    $labor_cost_price['requested_amount'] = bcmul($labor_cost_price['labor_cost_price'], $labor_cost_price['square'], 2);
                }
                db('capital')->where(['capital_id' => $item['projectId']])->update($requested_amount);
                $app_user_order_capital = Db::connect(config('database.db2'))->table('app_user_order_capital')->join('app_user', 'app_user.id=app_user_order_capital.user_id', 'left')->where('app_user_order_capital.capital_id', $item['projectId'])->whereNull('app_user_order_capital.deleted_at')->field('app_user_order_capital.*,app_user.origin,app_user.assist')->select();
                // $personal_price         = 0;
                $originPrice            = [];
                $normalPrice            = [];
                foreach ($app_user_order_capital as $list) {
                    if ($list['origin'] == 2) {
                        $originPrice[] = $list;
                    }
                    if ($list['origin'] == 1 && $list['assist'] == 0) {
                        $normalPrice[] = $list;
                    }
                }
                // $personal_price = array_sum(array_column($app_user_order_capital, 'personal_price'));
                $cooperation_price = array_sum(array_column($originPrice, 'cooperation_price'));
                if ($order_times['change_work_time'] > 1720724400) {
                    //$item['pri']=bcsub(bcsub($item['pri'],$labor_cost_price['labor_cost_reimbursement'],2),$common->availableReimbursementLimit($data['order_id'],$item['projectId']),2);
                }
                $laborCcostPrice        += $labor_cost_price['requested_amount'];
                $OldPri                 += $labor_cost_price['labor_cost'];
                if ($cooperation_price > $item['pri'] && !empty($originPrice) && !empty($normalPrice) && $cooperation_price > 0) {
                    throw new Exception('如果要减少工费，请先把已派单协作的工费减少，不然就乱了');
                }

                $item['pri'] = bcsub($item['pri'], $cooperation_price, 2);
                $pri                    += $item['pri'];
                $work_time         = array_sum(array_column($normalPrice, 'work_time'));
                if ($work_time == 0) {
                    if ($app_user_order_capital) {
                        Db::connect(config('database.db2'))->table('app_user_order_capital')->where('capital_id', $item['projectId'])->update(['personal_price' => 0, 'total_price' => $item['pri']]);
                    }
                } else {
                    foreach ($app_user_order_capital as $value) {
                        $orderCapital      = db('large_reimbursement', config('database.zong'))->where('order_id', $value['order_id'])->where('user_id', $value['user_id'])->where('status', 1)->sum('money');
                        $orderCapitalMoney = db('app_user_order_capital', config('database.db2'))->where('order_id', $value['order_id'])->where('id', '<>', $value['id'])->where('user_id', $value['user_id'])->whereNull('deleted_at')->sum('personal_price');
                        if ($orderCapital > $orderCapitalMoney + sprintf('%.2f', $item['pri'] * $value['work_time'] / $work_time)) {
                            throw new Exception('过审大工地结算金额超过清单工资');
                        }
                        $app_user_order_capital_labor_costs     = db('app_user_order_capital_labor_costs')->where('order_id', $value['order_id'])->where('capital_id', $value['capital_id'])->sum('personal_price');
                        if ($app_user_order_capital_labor_costs > $item['pri']) {
                            throw new Exception('【' . $labor_cost_price['class_b'] . '】清单已经支出快结工费:' . $app_user_order_capital_labor_costs . ',所以修改的金额不能小于' . $app_user_order_capital_labor_costs);
                        }
                        if ($value['work_time'] == 0) {
                            $updata = ['personal_price' => 0, 'total_price' => $item['pri']];
                        } else {
                            if ($value['origin'] == 1 && $value['assist'] == 0) {

                                $updata = ['personal_price' => sprintf('%.2f', $item['pri'] * $value['work_time'] / $work_time), 'total_price' => $item['pri']];
                            } elseif ($value['origin'] == 1 && $value['assist'] == 1) {

                                $updata = ['total_price' => $item['pri']];
                            } else {
                                $updata = ['total_price' => $item['pri']];
                            }
                        }
                        Db::connect(config('database.db2'))->table('app_user_order_capital')->where('id', $value['id'])->update($updata);
                    }
                }
            }

            if ($OldPri != $pri) {
                if (!empty($laborCcostPrice)) {
                    if ($pri / $laborCcostPrice > 1 + $order_setting['master_salary_rate'] / 100) {
                        throw new Exception('超过系统设置人工费，请在企业微信上做超限申请');
                    }
                }
            }
            $leaderList = [];
            if (!empty($leader)) {
                foreach ($leader as $k => $item) {
                    foreach ($leaders as $datum) {
                        if ($item == $datum['masterId']) {
                            $leaderList[$k]['user_id']   = $item;
                            $leaderList[$k]['projectId'] = $datum['projectId'];
                            $leaderList[$k]['leader']    = 0;
                        }
                    }
                }
            }
            $up_time = empty($data['up_time']) ? '' : strtotime($data['up_time'] . ' 23:59:59');
            $res     = db('startup')->where(['orders_id' => $data['order_id']])->find();
            $envelopes_id=0;
            if (!isset($data['type'])) {
                if (empty($data['shi_id']) && !empty($data['shi_id'])) {
                    throw new Exception('请至少选择一个师傅');
                }
                $us = db('order')
                    ->field('order.ification,order.telephone,co.con_time,co.contracType,order.pro_id2,order.tui_jian,order.tui_role,order.pro_id')
                    ->join('contract co', 'order.order_id=co.orders_id', 'left')
                    ->where('order_id', $data['order_id'])->find();
                $ca = db('envelopes')->where(['ordesr_id' => $data['order_id'], 'type' => 1])->field('give_money,gong,envelopes_id')->find();
               
                if (!empty($data['shi_id'])) {
                    $uss['order_id']       = $data['order_id'];
                    $uss['remark']         = $data['con'];
                    $uss['user_ids']       = $data['shi_id'];
                    $uss['plan_start_at']  = empty($data['sta_time']) ? '' : strtotime($data['sta_time']);
                    $uss['plan_end_at']    = $up_time;
                    $uss['plan_work_time'] = $ca['gong']; //师傅ID
                    $uss['leaders']        = $data['leader']; //师傅ID
                    $uss['leader']         = json_encode($leaderList); //师傅ID
                    $uss['ascription']     = $this->us['store_id']; //师傅ID
                    $uss['con_time']       = $us['con_time']; //师傅ID
                    $uss['store_id']       = $this->us['store_id']; //师傅ID
                    $uss['city']           = config('city'); //师傅ID
                    $result                = send_post(UIP_SRC . "/support-v1/order/add", $uss);
                    $results               = json_decode($result, true);
                    if ($results['code'] != 200) {
                        throw new Exception($results['msg']);
                    }
                }

                $o =
                    [
                        'sta_time' => empty($data['sta_time']) ? '' : strtotime($data['sta_time']),
                        'up_time' => $up_time,
                        'con' => $data['con'], //备注
                        'handover' => '',
                        'update_time' => $deleteTime,

                    ];
                    if(strtotime($data['sta_time']) !=$res['sta_time']){
                         $envelopes_id=$ca['envelopes_id'];
                    }
                if ($res) {
                    if ($res['created_time'] == 0) {
                        $o['created_time'] = $deleteTime;
                    }
                    db('startup')->where('orders_id', $data['order_id'])->update($o);
                    $startupId = $res['startup_id'];
                    db('startup_handover')->where('startup_id', $startupId)->delete();
                } else {
                    $o['orders_id']           = $data['order_id'];
                    $o['created_time']        = $deleteTime;
                    $common->StartJournal($data['order_id'], $this->us['user_id'], $this->us['username'], 2, '确认开工时间', 1);
                    $res                      = db('startup')->insertGetId($o);
                    $startup_id['startup_id'] = $res;
                    $startupId                = $startup_id['startup_id'];
                }
                $MultimediaResourcesImgs = [];
                if (!empty($handover)) {
                    foreach ($handover as $k => $item) {
                        $MultimediaResourcesImgs[$k]['path'] = $item['imgUrl'];
                        $handoverList[$k]['img_url']            = $item['imgUrl'];
                        $handoverList[$k]['no_watermark_image'] = $item['imgUrl'];
                        if (isset($item['oldImgUrl']) && !empty($item['oldImgUrl'])) {
                            $handoverList[$k]['no_watermark_image'] = $item['oldImgUrl'];
                        }

                        $handoverList[$k]['remarks']    = $item['remarks'];
                        $handoverList[$k]['startup_id'] = $startupId;
                    }
                    db('startup_handover')->insertAll($handoverList);
                    db('order_resource')->where(['order_id' => $data['order_id'], 'type' => 8])->update(['deleted_at' => $deleteTime]);
                    $common->MultimediaResources($data['order_id'], $this->us['user_id'], $MultimediaResourcesImgs, 8);
                }

                if (!empty($startup_id)) {
                    db('order')->where(['order_id' => $data['order_id'], 'assignor' => $this->us['user_id']])->update($startup_id);
                }
            }
             // 6. 批量处理 app_user_confirm_order（替换循环update，减少锁竞争）
            if (!empty($toDeleteConfirmOrder)) {
                // 批量软删除旧记录
                foreach($toDeleteConfirmOrder as $i){
                     db('app_user_confirm_order')
                    ->where('delete_time', 0)
                    ->where( $i)->update(['delete_time' => $deleteTime]);
                }
               
              // 批量插入新记录
                if (!empty($toInsertConfirmOrder)) {
                    db('app_user_confirm_order')->insertAll($toInsertConfirmOrder);
                }
            }
             if ($envelopes_id != 0) {
                $op = $capital->ganttChart($data['order_id'], $envelopes_id);
                $list     = $detailedWorkProcess->duration($op, 2, 0);
                $systemTag     = isset($data['systemTag']) ? $data['systemTag'] : 0;
                $tageList = $common->gantt($list, 2, $data['order_id'], $envelopes_id, $systemTag, strtotime($data['sta_time']));
                if ($tageList['weekday'] == 1) {
                    $tageList['weekday'] = 2;
                }
                db('envelopes_gantt_chart')->insert(['envelopes_id' => $envelopes_id, 'order_id' => $data['order_id'], 'picture' => '', 'created_time' => $deleteTime, 'result' => json_encode(['list' => $tageList['list'], 'date' => $tageList['date'], 'ganttDay' => $tageList['ganttDay'], 'weekday' => $tageList['weekday']]), 'duration' => $tageList['weekday'], 'type' => 2,'form'=>2]);
            }
            db()->commit();
            $shi_id = db('app_user_order_capital')->where('order_id', $data['order_id'])->whereNull('deleted_at')->column('user_id');
            db('startup')->where('startup_id', $startupId)->update(['xiu_id' => implode(",", array_unique($shi_id))]);
            if (!empty($redisKeysToDel)) {
                foreach ($redisKeysToDel as $t) {
                    $redis->del($t);
                }
            }
             if (!empty($redisKeysToyuyueDel)) {
                foreach ($redisKeysToyuyueDel as $t) {
                    $redis->del($t);
                }
            }
           r_date([], 200, '新增成功');
        } catch (Exception $e) {
            db()->rollback();
            r_date([], 300, $e->getMessage());
        }
    }
    
    /*
     * 店铺成交量
     */
    public function turnover_day(OrderModel $orderModel)
    {
        $timedata = $this->day_param(3);
        
        $start_timestamp = $timedata['start_timestamp'];
        // $end_timestamp = $timedata['end_timestamp'];
        $day              = $timedata['day'];
        $order_num        = [];
        $order_turnover   = [];
        $order_cost       = [];
        $material_usage   = [];
        $reimbursement    = [];
        $profit           = [];
        $order_unit_price = [];
        for ($i = $day; $i > -1; $i--) {
            $_begin = $start_timestamp + $i * 86400;
            $_end   = $start_timestamp + 86399 + $i * 86400;
            $order  = $orderModel->order_list($timedata['type'], $_begin, $_end, empty($timedata['user_id']) ? $this->us['user_id'] : $timedata['user_id'], $this->us['store_id']);
            
            //成交额
            $turnover         = order_for_turnover($order);
            $order_num[]      = [
                'time' => date('Y/m/d', $_begin),
                'data' => count($order),
            ];
            $order_turnover[] = [
                'time' => date('Y/m/d', $_begin),
                'data' => $turnover,
            ];
            
            if ($timedata['Difference'] == 4) {
                if ($turnover > 0) {
                    $unit_price = sprintf("%.2f", ($turnover / count($order)));
                } else {
                    $unit_price = 0;
                }
                $order_unit_price[] = [
                    'time' => date('Y/m/d', $_begin),
                    'data' => $unit_price,
                ];
            } elseif ($timedata['Difference'] == 5) {
                
                //预计人工费
                $order_cost[] = [
                    'time' => date('Y/m/d', $_begin),
                    'data' => order_for_artificial($order),
                ];
                //预计材料费
                $material_usage[] = [
                    'time' => date('Y/m/d', $_begin),
                    'data' => order_for_Finance($order),
                ];
                //报销费(只要实际报销)
                $reimbursement[] = [
                    'time' => date('Y/m/d', $_begin),
                    'data' => order_for_outlay($order),
                ];
                $profit[]        = [
                    'time' => date('Y/m/d', $_begin),
                    'data' => sprintf("%.2f", ($turnover - order_for_artificial($order) - order_for_Finance($order) - order_for_outlay($order))),
                ];
                
            } else if ($timedata['Difference'] == 6) {
                
                //实际人工费
                $order_cost[] = [
                    'time' => date('Y/m/d', $_begin),
                    'data' => order_for_reality_artificial($order),
                ];
                //实际材料费
                $material_usage[] = [
                    'time' => date('Y/m/d', $_begin),
                    'data' => order_for_reality_material($order),
                ];
                //报销费(只要实际报销)
                $reimbursement[] = [
                    'time' => date('Y/m/d', $_begin),
                    'data' => order_for_outlay($order),
                ];
                $profit[]        = [
                    'time' => date('Y/m/d', $_begin),
                    'data' => sprintf("%.2f", ($turnover - order_for_reality_artificial($order) - order_for_reality_material($order) - order_for_outlay($order))),
                ];
            }
            
            
        }
        r_date(['order_num' => $order_num, 'order_turnover' => $order_turnover, 'order_unit_price' => $order_unit_price, 'order_cost' => $order_cost, 'material_usage' => $material_usage, 'reimbursement' => $reimbursement, 'profit' => $profit], 200, '操作成功');
        
    }
    
    /*
       * 获取清单列表
       */
    public function cooperation(Common $common)
    {
        $data            = Authority::param(['orderId']);
        $capitalRelation = Db::connect(config('database.db2'))->table('app_user')
            ->field('GROUP_CONCAT(capital_value.title) as title,capital.class_b,capital.labor_cost_price as laborCostPrice,capital.square,capital.company,capital.labor_cost,capital.labor_cost_reimbursement,capital.categoryName,app_user.username,app_user_order_capital.capital_id,app_user_order_capital.user_id,app_user_order.last_saved,app_user_order_capital.cooperation_price as personal_price,app_user_order_capital.cubic_meter,app_user_order.plan_start_at,app_user_order_capital.reimbursement_id,capital.requested_amount as requestedAmount')
            ->join('app_user_order_capital', 'app_user_order_capital.user_id=app_user.id', 'left')
            ->join('app_user_order', 'app_user_order_capital.order_id=app_user_order.order_id and app_user_order.user_id=app_user_order_capital.user_id', 'left')
            ->join('capital', 'capital.capital_id=app_user_order_capital.capital_id', 'left')
            ->join('capital_value', 'app_user_order_capital.capital_id=capital_value.capital_id', 'left')
            ->where('capital.types', 1)
            ->where('app_user.origin', 2)
            ->whereNUll('app_user_order_capital.deleted_at')
            ->where('app_user_order_capital.order_id', $data['orderId'])
            ->group('app_user.id,app_user_order_capital.capital_id')
            ->select();
        
        $result   = array();
        $tageList = [];
        
        foreach ($capitalRelation as $k => $list) {
            $capitalRelation[$k]['reimbursement_ids'] = [];
            $personal_price=Db::connect(config('database.db2'))->table('app_user_order_capital')->whereNUll('deleted_at')->where('capital_id', $list['capital_id'])->field('sum(personal_price+cooperation_price) as personal_price')->select();
            $personal_price=empty($personal_price)?0:$personal_price[0]['personal_price'];
            $capital_minus_beforehand=db('capital_minus_beforehand')->where('capital_id', $list['capital_id'])->where('delete_time', 0)->where('types', 1)->select();
            $dangCapital_minus_beforehand=db('capital_minus_beforehand')->where('minus_id', $list['capital_id'])->where('delete_time', 0)->where('types', 1)->select();
            $isEdit=0;
            if (!empty($capital_minus_beforehand) || !empty($dangCapital_minus_beforehand)) {
                $isEdit=1;
            }
            
            $approval  = Db::connect(config('database.zong'))->table('approval')->where('relation_id', $list['capital_id'])->where('status', 0)->where('type', 8)->select();
            if(!empty($approval)){
                $isEdit=1;
            }
            $list['isEdit'] = $isEdit;
            $list['available'] = $list['labor_cost']-$list['labor_cost_reimbursement']-$common->availableReimbursementLimit($data['orderId'],$list['capital_id'])-($personal_price-$list['personal_price']);
            $list['cost'] =$list['labor_cost_reimbursement']+$common->availableReimbursementLimit($data['orderId'],$list['capital_id'])+($personal_price-$list['personal_price']);
            if ($list['reimbursement_id'] != 0) {
                $list['reimbursement_ids'][] = $list['capital_id'];
            }
            $list['content']             = Db::connect(config('database.db2'))->table('app_user_order_capital_relation')->whereNUll('deleted_at')->where('capital_id', $list['capital_id'])->count();
            $result[$list['username']][] = $list;
            
        }
        foreach ($result as $k => $list) {
            
            $schemeTag['title']            = $k;
            $schemeTag['state']            = empty($list[0]['last_saved']) ? 0 : 1;
            $schemeTag['reimbursement']    = empty($list[0]['reimbursement_ids']) ? 0 : 1;
            $schemeTag['mastId']           = $list[0]['user_id'];
            $schemeTag['lastSaved']        = empty($list[0]['last_saved']) ? "" : date('Y-m-d h:i:s', $list[0]['last_saved']);
            $schemeTag['mobilizationTime'] = empty($list[0]['plan_start_at']) ? "" : date('Y-m-d h:i:s', $list[0]['plan_start_at']);
            $schemeTag['data']             = $result[$k];
            $tageList[]                    = $schemeTag;
        }
        
        $result1   = array();
        $tageList1 = [];
        
        foreach ($tageList as $k => $list) {
            $result1 = [];
            foreach ($list['data'] as $l) {
                $result1[$l['categoryName']][] = $l;
            }
            $tageList[$k]['data'] = $result1;
            
        }
        
        foreach ($tageList as $k => $list) {
            $tageList2 = [];
            foreach ($list['data'] as $k1 => $l) {
                $tageList1['title'] = $k1;
                $tageList1['data']  = $list['data'][$k1];
                
                $tageList2[] = $tageList1;
            }
            $tageList[$k]['data'] = $tageList2;
            
        }
        r_date($tageList, 200);
    }
    
    /*
        * 根据orderId获取协作师傅
        */
    public function getTheCooperationMaster()
    {
        $data = Authority::param(['orderId']);
        
        $app_user = Db::connect(config('database.db2'))->table('app_user_order_capital')
            ->join('app_user', 'app_user.id=app_user_order_capital.user_id', 'left')
            ->where('app_user.checked', 1);
        if (isset($data['username']) && $data['username'] != '') {
            $app_user->whereLike('app_user.username', "%{$data['username']}%");
        }
        
        $user = $app_user
            ->where('app_user.status', 1)
            ->where('app_user.origin', 2)
            ->join(config('database')['database'] . '.store', 'app_user.store_id=store.store_id', 'left')
            ->field('app_user.id as user_id,app_user.username')
            ->group('app_user.id')
            ->where('app_user_order_capital.order_id', $data['orderId'])
            ->select();
        
        
        r_date($user, 200);
        
    }
    
    /*
     * 获取根据师傅获取清单列表
     */
    public function getMastCooperation()
    {
        $data            = Authority::param(['orderId', 'mastId']);
        $capitalRelation = Db::connect(config('database.db2'))->table('app_user_order_capital')
            ->field('GROUP_CONCAT(capital_value.title) as title,capital.class_b,capital.square,capital.labor_cost_price as laborCostPrice,capital.company,capital.labor_cost,capital.categoryName,app_user_order_capital.capital_id,app_user_order_capital.user_id,app_user_order_capital.cooperation_price as personal_price,app_user_order_capital.cubic_meter,capital.requested_amount as requestedAmount')
            ->join('capital', 'capital.capital_id=app_user_order_capital.capital_id', 'left')
            ->join('capital_value', 'app_user_order_capital.capital_id=capital_value.capital_id', 'left')
            ->where('capital.types', 1)
            ->whereNUll('app_user_order_capital.deleted_at')
            ->where('app_user_order_capital.order_id', $data['orderId'])
            ->where('app_user_order_capital.user_id', $data['mastId'])
            ->group('app_user_order_capital.capital_id')
            ->select();
        
        $result     = array();
        $tageList   = [];
        foreach ($capitalRelation as $k => $list) {
            $result[$list['categoryName']][] = $list;
            
        }
        foreach ($result as $k => $list) {
            $schemeTag['title'] = $k;
            $schemeTag['data']  = $result[$k];
            $tageList[]         = $schemeTag;
        }
        
        r_date($tageList, 200);
    }
    
    /*
  * 提交协作工费
  *
  */
    public function submitCooperativeLaborCost(Common $common)
    {
        $data = Authority::param(['orderId', 'mastId', 'mobilizationTime', 'cooperationData']);
        $mast = json_decode($data['cooperationData'], true);
        if (empty($data['mobilizationTime'])) {
            r_date(null, 300, "请输入进场时间");
        }
        
        Db::connect(config('database.db2'))->startTrans();
        try {
            //协作列表
            $notCooperationList = Db::connect(config('database.db2'))->table('app_user_order_capital')->whereNUll('app_user_order_capital.deleted_at')->where('order_id', $data['orderId'])->where('user_id', $data['mastId'])->count();
            //除掉协作列表
            $cooperationList = Db::connect(config('database.db2'))->table('app_user_order_capital')->join('app_user', 'app_user.id=app_user_order_capital.user_id', 'left')
                ->field('app_user_order_capital.work_time,app_user_order_capital.id,app_user_order_capital.capital_id,app_user_order_capital.total_price,app_user_order_capital.cooperation_price,app_user.assist')
                ->whereNUll('app_user_order_capital.deleted_at')
                ->where('order_id', $data['orderId'])
                ->where('app_user.origin', 1)
                ->where('app_user.assist',0)
                ->select();
            $mastFilter      = [];
            foreach ($mast as $l) {
                if ($l['cubic_meter'] >'-1'  && $l['personal_price'] >'-1') {
                    $mastFilter[] = $l;
                }
            }
            if ($notCooperationList != count($mastFilter)) {
                r_date(null, 300, "请填写完所有内容后提交");
            }
            $sumTime = [];
            
            foreach ($cooperationList as $o) {
                $result[$o['capital_id']][] = $o;
            }
            foreach ($mastFilter as $list) {
                $capital     = \db('capital')->where('capital_id', $list['capital_id'])->field('labor_cost,square,class_b,labor_cost_reimbursement')->find();
                $cubic_meter = Db::connect(config('database.db2'))->table('app_user_order_capital')->whereNUll('app_user_order_capital.deleted_at')->where('cubic_meter', '<>', 0)->where('user_id', '<>', $data['mastId'])->where('order_id', $data['orderId'])->where('capital_id', $list['capital_id'])->sum('cubic_meter');
                foreach ($cooperationList as $k => $item) {
                    if ($list['capital_id'] == $item['capital_id']) {
                        $personal_price                     = Db::connect(config('database.db2'))->table('app_user_order_capital')->whereNUll('app_user_order_capital.deleted_at')->where('cubic_meter', '<>', 0)->where('user_id', '<>', $data['mastId'])->where('order_id', $data['orderId'])->where('capital_id', $item['capital_id'])->sum('cooperation_price');
                        $kl=$common->availableReimbursementLimit($data['orderId'],$item['capital_id']);
                        $cooperationList[$k]['total_price'] = $capital['labor_cost']- ($capital['labor_cost_reimbursement']+$kl)- $list['personal_price'] - $personal_price;
                    }
                    
                }
                if ($capital['square'] < $list['cubic_meter'] + $cubic_meter) {
                    throw  new  Exception($capital['class_b'] . '清单，超出可剩余方量，请调整');
                }
                $user[] = [
                    'user_id' => $data['mastId'],
                    'order_id' => $data['orderId'],
                    'capital_id' => $list['capital_id'],
                    'total_price' => $capital['labor_cost'],
                    'work_time' => 1,
                    'cooperation_price' => $list['personal_price'],
                    'personal_price' => 0,
                    'cubic_meter' => $list['cubic_meter'],
                    'created_at' => time(),
                    'half_price' => 0,
                ];
                
            }
            if (!empty($cooperationList)) {
                
                foreach ($cooperationList as $l => $o) {
                    foreach ($result as $k => $o1) {
                        if ($o['capital_id'] == $k) {
                            $work_time                             = array_sum(array_column($result[$k], 'work_time'));
                            $cooperationList[$l]['personal_price'] = $o['work_time'] == 0 ? '0.00' : sprintf('%.2f', $o['total_price'] * $o['work_time'] / $work_time);
                        }
                        
                    }
                    
                }
                foreach ($cooperationList as $listItem) {
                    if ($listItem['total_price'] < 0) {
                        throw  new  Exception('清单总工费超出系统工费，请调整');
                    }
                    Db::connect(config('database.db2'))->table('app_user_order_capital')->where('id', $listItem['id'])->update(['personal_price' => $listItem['personal_price'], 'total_price' => $listItem['total_price']]);
                }
            }
            
            $last_saved = time();
            Db::connect(config('database.db2'))->table('app_user_order')->where('order_id', $data['orderId'])->where('user_id', $data['mastId'])->update(['last_saved' => $last_saved, 'plan_start_at' => strtotime($data['mobilizationTime'])]);
            if (!empty($user)) {
                Db::connect(config('database.db2'))->table('app_user_order_capital')->where('order_id', $data['orderId'])->where('user_id', $data['mastId'])->update(['deleted_at' => time(), 'cancel_shopowner' => 1]);
            }
            Db::connect(config('database.db2'))->table('app_user_order_capital')->insertAll($user);
            sendOrder($data['orderId']);
            Db::connect(config('database.db2'))->commit();
            r_date(date('Y-m-d H:i:s', $last_saved), 200);
        } catch (Exception $e) {
            Db::connect(config('database.db2'))->rollback();
            r_date(null, 300, $e->getMessage());
        }
    }
    
    /*
   * 费用报销
   */
    public function cooperationReimbursement(Approval $approval, OrderModel $orderModel, MaterialScience $materialScience, Common $common)
    {
        
        $data = Request::instance()->post();
        db()->startTrans();
        try {
            $state                = Db::table('order')->where('order_id',  $data['orderId'])->field('state,settlement_time,cleared_time')->find();
            if (!empty($state['cleared_time'])) {
                r_date(null, 300, '主合同已结算无法操作');
            }
            $capital_id     = json_decode($data['cooperationData'], true);
            $mainMaterialId = array_column($capital_id, 'capital_id');
            $io             = implode(',', $mainMaterialId);
            $offer          = $orderModel->TuiNewOffer($data['orderId']);
            $payment        = $common::order_for_payment($data['orderId']);
            
            $app_user = Db::connect(config('database.db2'))->table('app_user')->join('bank_card', 'bank_card.binding_uid=app_user.id and category=2', 'left')->where('id', $data['mastId'])->find();
            if (empty($app_user['bank_card_number'])) {
                throw new Exception('协作师傅未绑定银行卡');
            }
            $offer = $orderModel->TuiNewOffer($data['orderId']);
            $money = array_sum(array_column($capital_id, 'personal_price'));
            if ($money == 0) {
                throw new Exception('报销金额不能为0');
            }
            if (empty($data['sp_no'])) {
                throw new Exception('收据编号不能为空');
            }
            if (empty($data['voucher'])) {
                throw new Exception('报销凭证不能为空');
            }
            $moneyList = db('reimbursement')->where('order_id', $data['orderId'])->where('status', '<>', 2)->where('classification', 3)->sum('money');
            if ($moneyList + $money > $payment[4]) {
                throw new Exception('报销金额不能大于收款金额');
            }
            $reimbursementList = db('reimbursement')->where(['order_id' => $data['orderId'], 'reimbursement_name' => $app_user['username'] . '协作师傅请款', 'money' => $money, 'status' => ['<>', 2]])->find();
            if (!empty($reimbursementList)) {
                throw new Exception('已提交');
            }
            $op = ['order_id' => $data['orderId'], 'reimbursement_name' => $app_user['username'] . '协作师傅请款', 'money' => $money, 'created_time' => time(), 'user_id' => $this->us['user_id'], 'status' => 0, 'sp_no' => '', 'classification' => 3, 'submission_time' => time(), 'shopowner_id' => $this->us['user_id'], 'capital_id' => $io, 'voucher' =>!empty($data['voucher']) ? serialize(json_decode($data['voucher'],true)) : '' , 'origin_collaborator' => 1];
            
            $reimbursementId = db('reimbursement')->insertGetId($op);
            if ($reimbursementId) {
                db('reimbursement_relation')->insertGetId(['reimbursement_id' => $reimbursementId, 'capital_id' => $io, 'bank_id' => $app_user['bank_id'], 'money' => $money,'receipt_number'=>$data['sp_no']]);
                $title = array_search(3, array_column($materialScience->list_reimbursement_type(2), 'type'));
                $title = $this->us['username'] . $materialScience->list_reimbursement_type(2)[$title]['name'] . '报销';
                Db::connect(config('database.db2'))->table('app_user_order_capital')->whereIn('capital_id', $io)->where('order_id', $data['orderId'])->whereNUll('deleted_at')->where('user_id', $data['mastId'])->update(['reimbursement_id' => $reimbursementId]);
                db()->commit();
                json_decode(sendOrder($data['orderId']), true);
                $approval->Reimbursement($reimbursementId, $title, $this->us['username'], 3);
                r_date(null, 200);
            }
            
        } catch (Exception $e) {
            db()->rollback();
            r_date(null, 300, $e->getMessage());
            
        }
        
    }
    
    /*
   * 是否标记工时
   */
    public function workingHours()
    {
        $data          = Authority::param(['orderId', 'userId', 'capitalId']);
        $work_time     = Db::connect(config('database.db2'))->table('app_user_order')
            ->field('app_user_order.status,app_user.quit_jobs,app_user.origin')
            ->join('app_user', 'app_user.id=app_user_order.user_id', 'left')
            ->where('app_user_order.order_id', $data['orderId'])
            ->where('app_user_order.user_id', $data['userId'])
            ->find();
        $order_setting = Db::connect(config('database.db2'))->table('order_setting')->where('order_id', $data['orderId'])->value('fast_salary');
        if ($order_setting == 2) {
            $completion_time = Db::connect(config('database.db2'))->table('auxiliary_project_list')->where('order_id', $data['orderId'])->where('capital_id', $data['capitalId'])->whereNull('delete_time')->value('completion_time');
            if (!empty($completion_time)) {
                r_date(null, 300, '该清单节点已验收通过，不能操作');
            }
        }
        $app_user_order_capital = Db::connect(config('database.db2'))->table('app_user_order_capital')->whereNull('deleted_at')->where('user_id', $data['userId'])->where('order_id', $data['orderId'])->where('capital_id', $data['capitalId'])->sum('work_time');
        if ($work_time['origin'] == 2 && $work_time['status'] > 1) {
            // r_date(null, 300, '该师傅已开工不能取消');
        } elseif ($work_time['origin'] == 1 && $app_user_order_capital != 0 && $work_time['quit_jobs'] == 0) {
            r_date(null, 300, '该师傅已标记工时不能取消');
        }
        r_date(null, 200);
    }
    
    /*
     * 客户惊喜服务添加
     */
    public function customerSurpriseService()
    {
        $data  = Authority::param(['order_id', 'content', 'images', 'video']);
        $state = \db('order')->where('order_id', $data['order_id'])->value('state');
        \db('surprise_service_record', config('database.zong'))->insert([
            'order_id' => $data['order_id'],
            'source_type' => 1,
            'source_user' => $this->us['user_id'],
            'order_state' => $state,
            'content_text' => $data['content'],
            'file_images' => $data['images'],
            'file_video' => empty($data['video']) ? '' : $data['video'],
            'add_time' => time(),
        ]);
        r_date(null, 200);
    }
    
    /*
        * 客户惊喜服务列表
        */
    public function customerSurpriseServiceList()
    {
        $data                    = Authority::param(['orderId']);
        $surprise_service_record = \db('surprise_service_record', config('database.zong'))->where('order_id', $data['orderId'])->select();
        foreach ($surprise_service_record as $k => $list) {
            if ($list['source_type'] == 2) {
                $surprise_service_record[$k]['username'] = '师傅' . Db::connect(config('database.db2'))->table('app_user')->where('id', $list['source_user'])->value('username');
            } else {
                $surprise_service_record[$k]['username'] = '店长' . \db('user')->where('user_id', $list['source_user'])->value('username');
            }
            $surprise_service_record[$k]['file_images'] = json_decode($list['file_images'], true);
            $surprise_service_record[$k]['file_video']  = json_decode($list['file_video'], true);
            $surprise_service_record[$k]['add_time']    = date('Y-m-d H:i:s', $list['add_time']);
        }
        
        r_date($surprise_service_record, 200);
    }
    
    /*
  * 主材列表
  */
    public function capitalList(Capital $capital)
    {
        $data        = Authority::param(['orderId', 'type','classification']);
        $capitalList = $capital
            ->field('detailed.reimbursement,capital.*')
            ->with('SpecsList')
            ->join('detailed','detailed.detailed_id=capital.projectId','left')
            ->where(['capital.ordesr_id' => $data['orderId'], 'capital.types' => 1, 'capital.enable' => 1])
            ->where(function ($quer) {
                $quer->where('capital.approve', 0)->whereOr('capital.approve', 1);
            });
        if ($data['type'] != 1) {
            $capitalList->where('capital.agency', 0);
            if($data['classification']==1){
                $capitalList->where('find_in_set(:id,reimbursement)', ['id' => 2])->whereIn('capital.settlement_method', [1,2]);
            }
            if($data['classification']==2){
                $capitalList->where('find_in_set(:id,reimbursement)', ['id' => 3])->whereIn('capital.settlement_method', [1,2]);
            }
            if($data['classification']==3){
                $capitalList->where('find_in_set(:id,reimbursement)', ['id' =>1])->whereIn('capital.settlement_method', [1,2]);
            }
            if($data['classification']==7){
                $capitalList->where('find_in_set(:id,reimbursement)', ['id' => 4])->whereIn('capital.settlement_method', [1,2]);
            }
            if($data['classification']==8){
                $capitalList->where('capital.settlement_method', 2);
            }
        }
        $capitalList= $capitalList->select();
        $array       = [];
        foreach ($capitalList as $k => $item) {
            $projectRemark=!empty($item['projectRemark'])?"【备注：".$item['projectRemark']."】":'';
            $array[$k]['reimbursement'] = $item['reimbursement'];
            $array[$k]['capital_id'] = $item['capital_id'];
            $array[$k]['class_b']    = $item['class_b'].$projectRemark;
            $array[$k]['company']    = $item['company'];
            $array[$k]['square']     = $item['square'];
            $array[$k]['un_Price']   = $item['un_Price'];
            $array[$k]['to_price']   = $item['to_price'];
            $array[$k]['specsList']  = implode('/', array_column($item['specs_list'], 'option_value_title'));
        }
        r_date($array, 200);
        
    }
    
    /*
     * 获取日期
     */
    public function workCalendar()
    {
        $data          = Authority::param(['month']);
        $work_calendar = db('work_calendar', config('database.zong'))->whereBetween('data_string', [$data['month'] . '-01', $data['month'] . '-31'])->field('year,month,day,week,is_work,type,data_string')->select();
        r_date($work_calendar, 200);
    }

    /*
     * 获取日期
     */
    public function workCalendarQuery()
    {
        $data          = Authority::param(['month', 'day']);

        $y = [];
        $baseDate = $data['month'];
        $targetWorkDays = $data['day'];

        // 1. 查询基准日期信息（必须包含在结果中）
        $baseCalendar = db('work_calendar', config('database.zong'))
            ->where('data_string', '=', $baseDate)
            ->field('year,month,day,week,is_work,type,data_string')
            ->find();
        if (!$baseCalendar) {
            return r_date([], 200); // 基准日期不存在，返回空
        }

        // 2. 初始化：包含基准日，统计已有的工作日数量
        $workDays = [];
        $workDays[] = $baseCalendar; // 强制包含基准日
        $count = $baseCalendar['is_work'] == 1 ? 1 : 0; // 基准日是工作日则计数1，否则0

        // 3. 从基准日次日开始，累计足够的工作日（直到满足targetWorkDays）
        $currentDate = $baseDate;
        while ($count < $targetWorkDays) {
            $currentDate = date('Y-m-d', strtotime($currentDate . ' +1 day')); // 下一天
            $calendar = db('work_calendar', config('database.zong'))
                ->where('data_string', '=', $currentDate)
                ->field('year,month,day,week,is_work,type,data_string')
                ->find();
            if (!$calendar) {
                break; // 无后续日期，终止
            }

            // 加入所有日期（确保连续），但仅统计工作日
            $workDays[] = $calendar;
            if ($calendar['is_work'] == 1) {
                $count++; // 工作日计数+1
            }
        }

        // 4. 处理结束日为周末的情况（即使是调班的工作日，若为周末也顺延）
        if (!empty($workDays)) {
            $lastDay = end($workDays);
            // 若最后一个工作日是周末（week=0/6），则顺延至下一个非周末的工作日
            while (in_array($lastDay['week'], [0, 6])) {
                $nextDate = date('Y-m-d', strtotime($lastDay['data_string'] . ' +1 day'));
                $nextDay = db('work_calendar', config('database.zong'))
                    ->where('data_string', '=', $nextDate)
                    ->field('year,month,day,week,is_work,type,data_string')
                    ->find();
                if (!$nextDay || $nextDay['is_work'] != 1) {
                    break; // 无有效工作日则终止
                }
                // 替换最后一天为下一个工作日，继续检查是否为周末
                array_pop($workDays);
                $workDays[] = $nextDay;
                $lastDay = $nextDay;
            }
        }

        // 5. 确保结果中工作日数量准确（若不足则按实际返回）
        $y = $workDays;
        r_date($y, 200);
    }
    
    /*
     *店长开工
     */
    public function StartAdding(Common $common)
    {
        $data = Request::instance()->post();
        Db::connect(config('database.db2'))->startTrans();
        try {
            $params   = request()->only(['order_id', 'describe', 'lng', 'lat', 'address']);
            $resource = json_decode($data['resource'], true);
            $time     = time();
            Db::table('order')->where('order_id', $params['order_id'])->update(['start_time' => $time]);
            $startup = Db::table('startup')->where('orders_id', $params['order_id'])->find();
            $gong = Db::table('envelopes')->where('ordesr_id', $params['order_id'])->where('type', 1)->value('gong');
            (new Common())->PushCompletion(1, $params['order_id']);
             $work_calendar = db('work_calendar', config('database.zong'))->where('data_string', '>=', date('Y-m-d', $time))->where('is_work', 1)->order('data_string ACS')->limit($gong)->field('year,month,day,week,is_work,type,data_string')->select();
             if(empty($startup)){
                    Db::table('startup')->insert(['sta_time' => $time, 'up_time' => strtotime($work_calendar[count($work_calendar) - 1]['data_string'] . ' 23:59:59'),'orders_id'=>$params['order_id'],'created_time'=>$time]);
             }else{
                    Db::table('startup')->where('orders_id', $params['order_id'])->update(['sta_time' => $time, 'up_time' => strtotime($work_calendar[count($work_calendar) - 1]['data_string'] . ' 23:59:59')]);
             }
             Db::connect(config('database.db2'))->table('app_user_order')->where(['order_id' => $data['order_id']])->where('plan_start_at', 0)->update(['plan_start_at' => $time, 'plan_end_at' => strtotime($work_calendar[count($work_calendar) - 1]['data_string'] . ' 23:59:59'), 'plan_work_time' => $gong * 24 * 60 * 60]);
            
            $SiteInspection = new SiteInspection();
            if (!empty($resource)) {
                $listNode                         = $SiteInspection->addResourceIds($resource);
                $params['no_watermark_image_ids'] = implode(',', $listNode['no_watermark_image']);
                $params['resource_ids']           = implode(',', $listNode['resource_ids']);
            }
            $params['describe']    = $data['describe'] ?? '';
            $params['user_id']     = $this->us['user_id'];
            $params['type']        = 1;
            $params['status']      = 1;
            $params['distinguish'] = 1;
            $params['title']       = "开工设置";
            $params['created_at']  = time();
            $params['updated_at']  = time();
            $orderNode             = Db::connect(config('database.db2'))->table('app_user_order_node')->insertGetId($params);
            $common->StartJournal($params['order_id'],$this->us['user_id'],$this->us['username']);
            db()->commit();
            Db::connect(config('database.db2'))->commit();
            openapiAddTask($data['order_id'],6,'店长开工','');
            r_date(null, 200);
        } catch (\Exception $e) {
            Db::connect(config('database.db2'))->rollBack();
            r_date(null, 300, $e->getMessage());
        }
    }
    
    /*
     * 获取录音翻译参数
     */
    public function ailiToke()
    {
        $AlibabaCloudToke = new AlibabaCloudToke();
        $parameters       = $AlibabaCloudToke->createToken();
        
        r_date($parameters['toke'], $parameters['code'], $parameters['message']);
    }
    /*
     * 开工设置弹窗
     */
    public function startSettingWindow()
    {
        $userId = $this->us['user_id'];
        $new_handover = [];
        if ($this->us['disclosure_plan'] == 1) {
            $new_handover = db('order')->field([
                'order.order_id',
                'order.cleared_time',
                'order.settlement_time',
                'ANY_VALUE(order.addres) as address', // 非聚合字段处理‌:ml-citation{ref="6" data="citationList"}
                // 'startup.sta_time',
                'FROM_UNIXTIME(order_times.signing_time,"%Y-%m-%d %H:%i:%s")as signing_time',
                // 'MAX(order_times.change_work_time) as change_work_time',
                'SUM(IF(startup_new_handover.type=1,1,0)) as type1_total',
                'SUM(IF(startup_new_handover.type=2,1,0)) as type2_total'
            ])
                ->join('order_aggregate', 'order.order_id=order_aggregate.order_id', 'left')
                ->join('startup_new_handover', 'order.order_id=startup_new_handover.order_id AND startup_new_handover.delete_time=0', 'LEFT')
                ->join('order_times', 'order_times.order_id=order.order_id', 'LEFT')
                ->join('startup', 'startup.orders_id=order.order_id', 'LEFT')
                ->where(function ($query) {
                    $query->whereNotNull('startup.sta_time')
                        ->whereOr('startup.sta_time', '>', 0);
                })
                ->where(function ($query) use ($userId) {
                    $query->where('order.assignor', $userId)
                        ->whereOr('order.deliverer', $userId);
                })->where('CASE
            WHEN order_aggregate.main_price=0 and order_aggregate.agent_price !=0  THEN order.settlement_time is  null or order.settlement_time =0
             WHEN order_aggregate.main_price !=0 and order_aggregate.agent_price =0  THEN  order.cleared_time is  null or order.cleared_time =0
             WHEN order_aggregate.main_price !=0 and order_aggregate.agent_price !=0 THEN  order.cleared_time is  null or order.cleared_time =0 or order.settlement_time is null or order.settlement_time =0 END
             ')
                ->where('order_times.change_work_time', '>', 1743134400)
                ->whereNull('order.cleared_time')
                ->whereRaw('UNIX_TIMESTAMP(FROM_UNIXTIME(order.start_time + 0)) < UNIX_TIMESTAMP() - 86400')
                ->group('startup_new_handover.order_id')
                ->having('type1_total = 0 OR type2_total = 0 OR startup_new_handover.order_id IS NULL')
                ->select();
            if (!empty($new_handover)) {
                foreach ($new_handover as $l => $item) {
                    $new_handover[$l]['title'] = '已开工大于1天，仍然未提交交底方案';
                    // $list[$l]['content']='已延期'.$item['s'].'天未确认';
                    $new_handover[$l]['content'] = '';
                    $new_handover[$l]['type'] = 2;
                    unset($new_handover[$l]['type2_total'], $new_handover[$l]['type1_total']);
                }
            }
        }
        $list = [];
        if ($this->us['confirm_work_time'] == 1) {
            $list = \db('order_times')
                ->join('order', 'order.order_id=order_times.order_id', 'left')
                ->join('user', 'user.user_id=order.assignor', 'left')
                ->join('order_start_delay', 'order_start_delay.order_id=order_times.order_id', 'left')
                ->join('startup', 'startup.orders_id=order_times.order_id', 'left')
                ->where('order_times.signing_time', '>', '1718294400')
                ->where('order_times.change_work_time', '>', '0')
                ->whereBetween('order.state', [1, 7])
                ->where(function ($quer) {
                    $quer->whereNUll('startup.sta_time')->whereor('startup.sta_time', 0);
                })->where('UNIX_TIMESTAMP(FROM_UNIXTIME(order_times.change_work_time+IFNULL(order_start_delay.delay_days,0)*24*3600,"%Y-%m-%d 00:00:00")) < unix_timestamp(now()) - 4*24*3600')
                ->where(function ($quer) use ($userId) {
                    $quer->where('order.assignor', $userId)->whereor('order.deliverer', $userId);
                })
                ->field([
                    'order.addres as address',
                    'order.order_id',
                    'FROM_UNIXTIME(order_times.signing_time,"%Y-%m-%d %H:%i:%s")as signing_time',
                    'order_times.change_work_time',
                    // 'if((unix_timestamp(now())- 4*24*3600)-UNIX_TIMESTAMP(FROM_UNIXTIME(order_times.change_work_time+IFNULL(order_start_delay.delay_days,0)*24*3600,"%Y-%m-%d 00:00:00"))>0,CEIL(((unix_timestamp(now())- 4*24*3600)-UNIX_TIMESTAMP(FROM_UNIXTIME(order_times.change_work_time+IFNULL(order_start_delay.delay_days,0)*24*3600,"%Y-%m-%d 00:00:00")))/(24*3600)),0) as s'
                ])->order('order_times.change_work_time asc')->select();
            foreach ($list as $l => $item) {
                $list[$l]['title'] = '正签3天，未确认开工日期';
                // $list[$l]['content']='已延期'.$item['s'].'天未确认';
                $list[$l]['content'] = '';
                $list[$l]['type'] = 2;
            }
        }
        $listDate = array_merge($new_handover, $list);
        if ($this->us['confirm_work_time'] == 1) {
            $constructionGroupToBeBuilt = \db('order', config('database.zong'))
                ->join('order_times', 'order.order_id=order_times.order_id', 'left')
                ->join('order_info', 'order.order_id = order_info.order_id', 'left')
                ->join('order_unique_code', 'order.order_id=order_unique_code.order_id', 'left')
                ->where('order.created_time', '>', 1753977600)
                ->whereBetween('order.state', [4, 7])
                ->where('if(order.order_agency=1,order.cleared_time IS NULL and order.settlement_time  IS NULL,order.cleared_time  IS NULL )')
                ->where('order_times.change_work_time', '>', 0)
                ->where('order_unique_code.is_crowd', 0)
                ->where('order_info.gong', '>', 1)
                ->where('UNIX_TIMESTAMP(FROM_UNIXTIME(order_times.change_work_time,"%Y-%m-%d 00:00:00")) < unix_timestamp(now()) - 4*24*3600')
                ->where(function ($quer) use ($userId) {
                    $quer->where('order.assignor', $userId)->whereor('order.deliverer', $userId);
                })
                ->field([
                    'order.addres as address',
                    'order.order_id',
                    'FROM_UNIXTIME(order_times.signing_time,"%Y-%m-%d %H:%i:%s")as signing_time',


                ])->order('order_times.change_work_time asc')->select();
            foreach ($constructionGroupToBeBuilt as $l => $item) {
                $constructionGroupToBeBuilt[$l]['title'] = '正签3天内，仍然未创建群聊。若已创建，请复制群聊编号复制到群名中，系统会5分钟扫描一次。PS：关键条件，一定是外部群（含外部客户）、一定要有益鸟AI机器人、一定要有群编码';
                $constructionGroupToBeBuilt[$l]['content'] = '';
                $constructionGroupToBeBuilt[$l]['type'] = 1;
                $constructionGroupToBeBuilt[$l]['isCrowd'] = 1;
            }
            if (!empty($constructionGroupToBeBuilt)) {
                $listDate = array_merge($listDate, $constructionGroupToBeBuilt);
            }
        }


        r_date($listDate, 200);
    }
    /*
     * 订单延期开工单
     */
    public function orderStartDelay(Common $common){
        $data = Request::instance()->post();
        $order_start_delay=db('order_start_delay')->where(['order_id'=>$data['orderId']])->count();
        if($order_start_delay>0){
            r_date(null,300,'仅可提交一次延期');
        }
        $common->StartJournal($data['orderId'],$this->us['user_id'],$this->us['username'],2,'延期天数'.$data['days'].'天,'.$data['checkReason']."备注：".$data['reason'],5);
        db('order_start_delay')->insert(['order_id'=>$data['orderId'],'delay_days'=>$data['days'],'delay_check_reason'=>$data['checkReason'],'delay_reason'=>$data['reason'],'user_id'=>$this->us['user_id'],'username'=>$this->us['username'],'create_time'=>time()]);
        r_date(null,200);
    }
    /**
     * 提效工具:适配业务的图片编辑工具
     */
    public function editToolText(){
        
        $list=[
            [
                'type'=>1,
                'title'=>"工种",
                'data'=>[
                    ['id'=>1,'title'=>"漆工",'icon'=>'https://imgaes.yiniaoweb.com/.uploads/painter.png'],
                    ['id'=>2,'title'=>"水电工",'icon'=>'https://imgaes.yiniaoweb.com/.uploads/electrician.png'],
                    ['id'=>3,'title'=>"木工",'icon'=>'https://imgaes.yiniaoweb.com/.uploads/carpentry.png'],
                    ['id'=>4,'title'=>"砖工",'icon'=>'https://imgaes.yiniaoweb.com/.uploads/brickwork.png'],
                    ['id'=>5,'title'=>"打拆",'icon'=>'https://imgaes.yiniaoweb.com/.uploads/Dismantle.png']
                ]
            ],
            // [
            //     'type'=>2,
            //     'title'=>"项目",
            //     'data'=>[
            //         [
            //             'id'=>"",
            //             'title'=>"项目1",
                        
                        
            //         ],
                    
                    
            //     ]
            // ],
            // [
            //     'type'=>3,
            //     'title'=>"工序",
            //     'data'=>[
            //         [
            //             'id'=>"",
            //             'title'=>"工序1",
                        
            //         ],
                   
                    
            //     ]
            // ],
            
        ];
        r_date(['pictureText'=>$list,'speedMarker'=>[['id'=>1, 'title'=>"项目",'data'=>[['id'=>1,'title'=>"满补刷新"],['id'=>2,'title'=>"铲除刷新"],['id'=>3,'title'=>"厨房整体翻新"],['id'=>4,'title'=>"卫生间整体翻新"],['id'=>5,'title'=>"水电改造需要现场交底"],['id'=>66,'title'=>"封窗"]]],['id'=>2,'title'=>"空间",'data'=>[['id'=>1,'title'=>"厨房"],['id'=>2,'title'=>"客卫"],['id'=>3,'title'=>"主卫"],['id'=>4,'title'=>"卧室"],['id'=>5,'title'=>"客厅"],['id'=>6,'title'=>"阳台"],['id'=>7,'title'=>"生活阳台"]]]],'precautions'=>[['id'=>1,'title'=>'冰箱不能断电！','icon'=>'https://imgaes.yiniaoweb.com/.uploads/attention.png','isWarn'=>1],['id'=>2,'title'=>'地板不能直接粘胶带','icon'=>'https://imgaes.yiniaoweb.com/.uploads/attention.png','isWarn'=>1],['id'=>3,'title'=>'建渣远离墙放','icon'=>'https://imgaes.yiniaoweb.com/.uploads/attention.png','isWarn'=>1],['id'=>4,'title'=>'施工噪音注意规避','icon'=>'https://imgaes.yiniaoweb.com/.uploads/attention.png','isWarn'=>1],['id'=>5,'title'=>'风雨天，门窗记着关闭','icon'=>'https://imgaes.yiniaoweb.com/.uploads/attention.png','isWarn'=>1]]],200);
    }
    /**
     * 标准动作内容提交
     */
    public function submissionOfDisclosureContent(Common $common){
        $param = Authority::param(['orderId', 'jsonData']);
        
        $order=db('order') ->where('order_id', $param['orderId'])->find();
        if(($order['order_agency']==0 &&$order['cleared_time']>0) || ($order['order_agency']==1 && $order['cleared_time']>0 && $order['settlement_time']>0)){
            r_date(null,300,'订单已经结算，无法修改（只有未结算的订单才可以修改或添加）');
        }
        db('startup_new_handover') ->where('order_id', $param['orderId'])->update(['delete_time'=>time()]);
        db('startup_new_handover_count')->where('order_id', $param['orderId'])->where('delete_time',0)->update(['delete_time' => time()]);
        $jsonData=json_decode($param['jsonData'],true);
        $newWorkmanship=$jsonData['newWorkmanship'];
        if ($newWorkmanship['pattern'] == 2) {
            $listArray = [];
            foreach ($newWorkmanship['json'] as $k => $item) {

                $array = [];
                if ($item['select'] == 1) {
                    foreach ($item['data'] as $value) {
                        if ($value['type'] == 1) {
                            $select = [];
                            foreach ($value['select'] as $val) {
                                if ($val['select'] == 1) {
                                    $select[] = ['id' => $val['id'], 'title' => $val['title']];
                                }
                            }
                            if (!empty($select)) {
                                $array[] = ['id' => $value['id'], 'title' => $value['title'], 'content' => $select, 'type' => $value['type']];
                            }
                        }
                        if ($value['type'] == 2 && !empty($value['inputEndStr'])) {
                            $array[] = ['id' => $value['id'], 'title' => $value['title'], 'content' => $value['inputEndStr'], 'type' => $value['type']];
                        }
                    }
                    if (!empty($array)) {
                        $listArray[$k]['title'] = $item['title'];
                        $listArray[$k]['id'] = $item['id'];
                        $listArray[$k]['data'] = $array;
                        foreach ($array as $v) {
                            $startup_new_handover_count = db('startup_new_handover_count')->insertGetId(['order_id' => $param['orderId'], 'project_id' => $item['id'], 'project_title' => $item['title'], 'data_id' => $v['id'], 'data_title' => $v['title'], 'type' => $v['type'], 'create_time' => time()]);
                            $startup_new_handover_count_content = [];
                            if (is_array($v['content'])) {

                                foreach ($v['content'] as $o) {
                                    $startup_new_handover_count_content[] = ['pid_id' => $startup_new_handover_count, 'content_id' => $o['id'], 'content' => $o['title'], 'create_time' => time()];
                                }
                            } else {

                                $startup_new_handover_count_content[] = ['pid_id' => $startup_new_handover_count, 'content_id' => $v['id'], 'content' => $v['content'], 'create_time' => time()];
                            }
                            db('startup_new_handover_count_content')->insertAll($startup_new_handover_count_content);
                        }
                    }
                }
            }
        }
        $list=[];
        
        $create_time=time();
        if ($jsonData['customerDemandId'] > 0) {
            array_push($list, ['id' => $jsonData['customerDemandId'], 'delete_time' => 0, 'content' => $jsonData['customerDemand'], 'type' => 1]);
        } else {
            array_push($list, ['content' => $jsonData['customerDemand'], 'order_id' => $param['orderId'], 'grouping' => '', 'create_time' => $create_time, 'type' => 1]);
        }
       
        if ($newWorkmanship['id'] > 0) {
            $content=$newWorkmanship['content'];
            $template_json='';
            if($newWorkmanship['pattern']==2){
                 $content=json_encode(array_values($listArray),JSON_UNESCAPED_UNICODE);
                 $template_json=json_encode($newWorkmanship['json'],JSON_UNESCAPED_UNICODE);
            }
            array_push($list, ['id' => $newWorkmanship['id'], 'delete_time' => 0, 'content' => $content, 'type' => 4,'pattern'=>$newWorkmanship['pattern'],'template_json'=>$template_json]);
        } else {
             $content=$newWorkmanship['content'];
              $template_json='';
            if($newWorkmanship['pattern']==2){
                 $template_json=json_encode($newWorkmanship['json'],JSON_UNESCAPED_UNICODE);
                 $content=json_encode(array_values($listArray),JSON_UNESCAPED_UNICODE);
            }
            array_push($list, ['content' => $content, 'order_id' => $param['orderId'], 'grouping' => '', 'create_time' => $create_time, 'type' => 4,'pattern'=>$newWorkmanship['pattern'],'template_json'=>$template_json]);
        }
        if ($jsonData['specialNeedId'] > 0) {
            array_push($list, ['id' => $jsonData['specialNeedId'], 'delete_time' => 0, 'content' => $jsonData['specialNeed'], 'type' => 5]);
        } else {
            array_push($list, ['content' => $jsonData['specialNeed'], 'order_id' => $param['orderId'], 'grouping' => '', 'create_time' => $create_time, 'type' => 5]);
        }
      
     
        foreach ($jsonData['demandSpaces'] as $value) {
            $md5=[];
            foreach ($value['images'] as $value1){
                $isOrderResource=\db('order_resource')->whereIn('md5',md5_file($value1))->find();
                if(empty($isOrderResource)){
                    $common->MultimediaResources($param['orderId'],$this->us['user_id'],$value1,15);
                }else{
                    $md5[]       = $isOrderResource['id'];
                }
            }
            $order_resource='';
            if(!empty($md5)){
                $order_resource=implode(',',$md5);
            }
            $resource_ids=[];
            if(!empty($value['images'])){
                $resource_ids=$common->addResourceListImg($value['images']);
            }
            if($value['id']>0){
                array_push($list,['id'=>$value['id'],'delete_time'=>0,'content'=>$value['content'],'grouping'=>$value['grouping'],'images'=>json_encode($value['images']),'images_annotation'=>$order_resource,'type'=>2,'resource_ids'=>empty($resource_ids)?'':implode(",",$resource_ids)]);   
            }else{
                array_push($list,['delete_time'=>0,'order_id'=>$param['orderId'],'content'=>$value['content'],'grouping'=>$value['grouping'],'images'=>json_encode($value['images']),'create_time'=>$create_time,'images_annotation'=>$order_resource,'type'=>2,'resource_ids'=>empty($resource_ids)?'':implode(",",$resource_ids)]);
            }
            
           
        }
        foreach ($jsonData['changeSynchronization'] as $value) {
            $md51=[];
            foreach ($value['images'] as $value1){
                $isOrderResource1=\db('order_resource')->whereIn('md5',md5_file($value1))->find();
                if(empty($isOrderResource1)){
                    $common->MultimediaResources($param['orderId'],$this->us['user_id'],$value1,15);
                }else{
                    $md51[]       = $isOrderResource1['id'];
                }
            }
            $order_resource1='';
            if(!empty($md51)){
                $order_resource1=implode(',',$md51);
            }
            $resource_ids=[];
            if(!empty($value['images'])){
                $resource_ids=$common->addResourceListImg($value['images']);  
            }
            if($value['id']>0){
                array_push($list,['id'=>$value['id'],'delete_time'=>0,'content'=>$value['content'],'grouping'=>'','app_work_type'=>$value['appWorkTypeId'],'images'=>json_encode($value['images']),'images_annotation'=>$order_resource1,'type'=>3,'resource_ids'=>empty($resource_ids)?'':implode(",",$resource_ids)]);   
            }else{
                array_push($list,['delete_time'=>0,'order_id'=>$param['orderId'],'content'=>$value['content'],'grouping'=>'','app_work_type'=>$value['appWorkTypeId'],'images'=>json_encode($value['images']),'create_time'=>$create_time,'images_annotation'=>$order_resource1,'type'=>3,'resource_ids'=>empty($resource_ids)?'':implode(",",$resource_ids)]);   
            }
           
        }  
        $startupNewHandover=new StartupNewHandover();
        $startupNewHandover->saveAll($list);
     
        r_date(null,200);
    }
    /**
     * 图片标注
     */
    public function imageOverlays(){
        $param = Authority::param(['imageUrl', 'labelJson','type']);
        $url=$param['imageUrl'];
        $headers = get_headers($url, 1);
        if (isset($headers['Content-Length'])) {
            $fileSize = $headers['Content-Length'];
            $size     = $fileSize;
        } else {
            $size = 0;
        }
        $mime_type = getimagesize($url)['mime'];
        $md5       = md5_file($url);
        $path      = parse_url($url)['path'];
        $type=15;
        if($param['type']==1){
            $type=16;
        }
        $labelJson=json_decode($param['labelJson'],true);
        $list= ['order_id' => 0, 'role_type' => 1, 'user_id' => $this->us['user_id'], 'type' =>$type, 'mime_type' => empty($mime_type) ? '' : $mime_type, 'path' => $path, 'size' => $size, 'md5' => $md5, 'status' => 1, 'created_at' => time(),'label_jsons'=>empty($labelJson)?'':$param['labelJson']];
        \db('order_resource')->insert($list);
        r_date(null,200);
    }
    /**
     * 预约施工日异常提醒
     */
    public function appointmentForConstruction(RedisPackage $redis)
    {
        $param = Authority::param(['orderId', 'userId', 'projectId']);
        $userIdList = json_decode($param['userId'], true);
        $orderId = $param['orderId'];
        $projectId = $param['projectId'];
        $listArray = [];
        $listTime = [];
        foreach ($userIdList as $item) {
            $userId = $item;
            $date = 0;
            $userdate = $redis->get("DateAssignment-".md5($orderId . $projectId . 'yuyue'));
            if ($userdate) {
                $userdateList = json_decode($userdate, true);
                if (!empty($userdateList)) {
                    foreach ($userdateList  as $v) {
                        if ($v['user_id'] == $userId) {
                            $date = $v['time'];
                        }
                    }
                }
            }
            if ($date != 0) {
                $list = $this->getScheduleString($userId, strtotime($date), 1);
                array_push($listTime, ['userId' => $userId, 'time' => strtotime($date)*1000]);
                if (!empty($list)) {
                    $state = 0;
                    if (strpos($list['data'][0],'当日有其他安排，无法派单，系统自动取消勾选') !== false) {
                        $state = 1;
                    }

                    $listArray[] = ['title' => $list['title'] . ':'  . $list['data'][0], 'user_id' => $userId, 'state' => $state];
                }
            }
        }
        $userdateTime = $redis->get("DateAssignment-" . md5($orderId . $projectId . 'time'));
        if ($userdateTime) {
            $userdateTime = json_decode($userdateTime, true);
            if(is_array($userdateTime)) {
                $list = array_merge($userdateTime, $listTime);
                $redis->set("DateAssignment-".md5($orderId . $projectId . 'time'), json_encode($list), 12000);
            }
        }else{
            $redis->set("DateAssignment-".md5($orderId . $projectId . 'time'), json_encode($listTime), 12000);
        }
        
        if (empty($userIdList)) {
            $redis->del("DateAssignment-".md5($orderId . $projectId . 'time'));
        }
      r_date(['list' => empty($listArray) ? null : $listArray, 'time' => $listTime], 200);
    }

     /**
      * 预约施工日快速回显时间
     */
    public function quickDisplayTime()
    {
        $param = Authority::param(['orderId', 'userId', 'projectId']);
        $userId=$param['userId'];
        $orderId=$param['orderId'];
        $projectId=json_decode($param['projectId'],true);
        $app_user_confirm_order = db('app_user_confirm_order')->where('app_user_id', $userId)->where('order_id', $orderId)->whereIn('status', [0,1])->where('delete_time', 0)->select();
        $list=[];
        foreach($projectId as $k=>$item){
             foreach($app_user_confirm_order as $k=>$val){
                if($item==$val['project_id']){
                    $date=$val['date'];
                    if($val['edit_time'] !=0){
                          $date=$val['edit_time'];
                    }
                    $list[$k]['time']=$date*1000;
                    $list[$k]['userId']=$userId;
                    $list[$k]['projectId']=$item;
                }
             
             }
        }
       r_date(empty($list)?null:$list, 200);
    }
    /**
     * 预约施工日快速异常提醒
     */
    public function quickMatchAppointmentForConstruction(RedisPackage $redis)
    {
        $param = Authority::param(['orderId', 'userId', 'date', 'projectId']);

        $date = $param['date'];
        $orderId = $param['orderId'];
        $userId = $param['userId'];
        $projectId = json_decode($param['projectId'], true);
        $listArray = [];
         $listTime = [];
        $title = '';
        if (is_numeric($date)) {
            $date=$date/1000;
            $date=date('Y-m-d',$date);
        }
        $list = $this->getScheduleString($userId, strtotime($date), 4);
        if (!empty($list)) {
            foreach ($list['data'] as $k => $v) {
                $state = 0;
                if (strpos($v, '当日有其他安排，无法派单，系统自动取消勾选') !== false) {
                    $state = 1;
                }

                $listArray[$k]['state'] = $state;
                $listArray[$k]['user_id'] = $userId;
                $listArray[$k]['title'] = $v;
            }
            $title = $list['title'];
        }
         if(!empty($projectId)){
            foreach ($projectId as $item) {
                 $app_user_confirm_order =db('app_user_confirm_order')->where('order_id',$orderId)->where('app_user_id',$userId)->where('project_id',$item)->where('status','<>',2)->order('id desc')->where('delete_time',0)->find();
                  $time= strtotime($date) * 1000;
                 if(!empty($app_user_confirm_order)){
                     $time=$app_user_confirm_order['date'];
                     if($app_user_confirm_order['edit_time'] !=0){
                        $time=$app_user_confirm_order['edit_time'];
                     }
                     $time=$time*1000;
                 }
                $listTime[] = ['userId' => $userId , 'time' => $time, 'projectId' => $item];
                $userdateTime = $redis->get("DateAssignment-" . md5($orderId . $item . 'time'));
                if ($userdateTime) {
                    $userdateTime = json_decode($userdateTime, true);
                    if (is_array($userdateTime)) {
                        $list = array_merge($userdateTime, [['userId' => $userId, 'time' =>$time]]);
                        $redis->set("DateAssignment-" . md5($orderId . $item . 'time'), json_encode($list), 12000);
                    }
                } else {
                   $redis->set("DateAssignment-".md5($orderId . $item . 'time'), json_encode([['userId' => $userId, 'time' =>$time]]), 12000);
                }
                
            } 
        }

        r_date(['list' => empty($listArray) ? null : $listArray, 'title' => $title, 'time' => $listTime], 200);
    }
    
    /**
     * 预约施工日确认
     */
    public function confirmTheTime(RedisPackage $redis)
    {
        $param = Authority::param(['orderId', 'date', 'userId', 'projectId', 'type']);
        $orderId = $param['orderId'];
        $projectId = $param['projectId'];
        $userId = $param['userId'];
        $date = $param['date'];
        $userdate = $redis->get('DateAssignment-'.md5($orderId . $projectId . 'yuyue'));
        $lists = [['time' => $date, 'user_id' => $userId]];
        if ($userdate) {
            $userList = json_decode($userdate, true);
            if(is_array($userList)) {
                $list = array_merge($userList, $lists);
                $redis->set("DateAssignment-".md5($orderId . $projectId . 'yuyue'), json_encode($list), 12000);
            }
        } else {
            $redis->set("DateAssignment-".md5($orderId . $projectId . 'yuyue'), json_encode($lists), 12000);
        }

        r_date(null, 200);
    }
    /**
     * 检查师傅是否派单
     * @param mixed $userId
     * @param mixed $time
     * @param mixed $type
     * @return never
     */

    public function getScheduleString($userId = 0, $time, $type)
    {

        // 1. 计算后3天的日期时间戳（年月日0点）及显示标签
        $dateInfo = [];
        for ($i = 0; $i < $type; $i++) {

            $date = strtotime(date('Y-m-d', $time)) + $i * 24 * 3600;

            $dateInfo[] = [
                'timestamp' => $date,
                'label' => date('m月d日', $date),

            ];
        }

        // 2. 构建查询条件
        $query = Db::table('app_user_scheduling')
            ->join('app_user',  'app_user_scheduling.user_id=app_user.id', 'left')
            ->field([
                'app_user.id as user_id',
                'app_user.username as master_name',
                'app_user_scheduling.date',
                'app_user_scheduling.day',
                'app_user_scheduling.arrangement',
                'app_user_scheduling.order_id',
                'app_user_scheduling.remark',
                'app_user_scheduling.arrange',

            ])
            ->whereIn('app_user_scheduling.date', array_column($dateInfo, 'timestamp'))
            ->whereNull('app_user_scheduling.deleted_at')
            ->where('app_user_scheduling.created_at', '>', '1755792000');

        // 如果指定了师傅ID则筛选
        if (!is_null($userId)) {
            $query->where('app_user.id', $userId);
        }
        // 假设 sample1 方法在当前控制器中存在，返回安排类型列表
        // $listArray = $this->sample1(1);
        // 执行查询

        $schedules = $query->select();
        // 处理师傅名称
        $masterName = '';
        if (!empty($schedules)) {
            $masterName = $schedules[0]['master_name'] ?? '';
        }
        $laber =  $masterName;
        if ($type != 1) {
            $laber =  $masterName.$dateInfo[0]['label'].'10月23日及后续3天，预约及排期情况';
        }
        $masterName = $laber;
        $scheduleParts = [];

        // 遍历每天的安排
        foreach ($dateInfo as $date) {
            $daySchedules = [];
            foreach ($schedules as $schedule) {
                if ($schedule['date'] == $date['timestamp']) {
                    $daySchedules[] = $schedule;
                }
            }
            // 日期前缀
            $datePrefix = "【" . $date['label'] . '】：';
            // 情况1：该日期没有任何排班记录（未操作排班）
            if (empty($daySchedules)) {
                $app_user_confirm_order = db('app_user_confirm_order')->where('app_user_id', $userId)->where('date', $date['timestamp'])->where('status', 0)->where('delete_time', 0)->count();
                if ($app_user_confirm_order != 0) {
                    $laber= db('app_user')->where('id', $userId)->value('username');
                    $scheduleParts[] = $datePrefix . '有' . $app_user_confirm_order . '店长预约施工未确认';;
                }
                continue;
            }
            // 情况2：有记录，检查是否有有效安排（arrangement=1）
            $hasValidArrangement = false;
            foreach ($daySchedules as $item) {
                if ($item['arrangement'] == 1) {
                    $hasValidArrangement = true;
                    break;
                }
            }
            // 情况2.1：有记录但无有效安排（全部arrangement=0）
            if (!$hasValidArrangement) {
                $leisure = [];
                foreach ($daySchedules as $item) {
                    if ($item['arrangement'] == 0 && $item['arrange'] !=1) {
                        $leisure[] = $item;
                    }
                }
                $leisure = array_unique($leisure, SORT_REGULAR);
                // 处理$leisure集合，匹配title并拼接remark
                $formattedLeisure = [];
                foreach ($leisure as $item) {

                    // 拼接成 "title - remark" 格式，处理可能的空remark
                    $formattedLeisure[] = $item['arrange'];
                }
                if (!empty($formattedLeisure)) {
                    $scheduleParts[] = $datePrefix . '当日有其他安排，无法派单，系统自动取消勾选';
                }


                continue;
            }
            // 情况3：有有效安排，区分上下午处理
            $morning = [];
            $afternoon = [];
            foreach ($daySchedules as $item) {
                if ($item['day'] == '0.5' && $item['arrangement'] == 1) {
                    $morning[] = '有安排';
                } elseif ($item['day'] == '-0.5' && $item['arrangement'] == 1) {
                    $afternoon[] = "有安排";
                }
            }
            $morning = array_unique($morning);
            $afternoon = array_unique($afternoon);

            // 拼接当天安排字符串
            $dayParts = [];


            if (!empty($morning) && empty($afternoon)) {
                $dayParts[] = '上午有安排';
            }

            // 处理下午安排
            if (!empty($afternoon) && empty($morning)) {
                $dayParts[] = '下午有安排';
            }
            // 处理上午安排
            if (!empty($morning) && !empty($afternoon)) {
                $dayParts[] = '全天有安排';
            }

            if (!empty($dayParts)) {
                // 特殊情况：全天无安排但arrangement=1的情况
                $scheduleParts[] = $datePrefix . implode('，', $dayParts);
            }
        }
        if (!empty($scheduleParts)) {
            return  ['title' => $laber, 'data' => $scheduleParts];
        } else {
            return  [];
        }
    }

   
      /**
     * 此清单派单所有师傅，都按照这个日期预约
     */
    public function dateReservation(RedisPackage $redis)
    {
        $param = Authority::param(['orderId', 'projectId']);
    //     $orderId = $param['orderId'];
    //     $projectId = $param['projectId'];
    //     $tt = $redis->get(md5($orderId . $projectId.'yuyue1'));
        $data=1;
    //    if ($tt) {
    //         $data = 0;
    //     }

        r_date($data, 200);
    }
    /**
     * 清单派单所有师傅，已经提交
     */
    public function dateReservationSubmit(RedisPackage $redis)
    {
        $param = Authority::param(['orderId', 'projectId']);
        // $orderId = $param['orderId'];
        // $projectId = $param['projectId'];
        // $redis->del(md5($orderId . $projectId.'yuyue1'));
        r_date(null, 200);
    }


}